package edu.nf.exam.util;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangl
 * @date 2021/6/8
 */
public class HttpUtils {

    public static String get(String url) {
        HttpRequest request = HttpRequest.get(url);
        return execute(request);
    }

    public static String post(String url, Map<String, Object> params) {
        HttpRequest request = HttpRequest.post(url);
        if(params != null && !params.isEmpty()){
            request.form(params);
        }
        return execute(request);
    }

    private static String execute(HttpRequest request){
        HttpResponse response = request.execute();
        String body = null;
        if(response.isOk()){
            body = response.body();
        }
        return body;
    }

    public static int upload(String url, String fileName, InputStream input){
        HttpResponse response = HttpRequest.post(url)
                .form("file", new InputStreamResource(input, fileName))
                .execute();
        return response.getStatus();
    }

    public static void delServiceFile(String url,String fileName){
        HashMap<String, Object> map = new HashMap<>();
        map.put("action","delete");
        map.put("selection",fileName);
        post(url,map);
    }

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();
        params.put("action", "delete");
        params.put("selection", "bb.txt");
        post("http://10.211.55.6:8089/uploads/", params);
    }
}
